package com.zjdiepu.www.biz.dh;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.InsuranceStatus;
import com.zjdiepu.www.base.enums.type.ModeIDType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.dao.base.SysUserMapper;
import com.zjdiepu.www.dao.dh.DhInsuranceRenewalMapper;
import com.zjdiepu.www.dao.other.OtherTaskAllocationMapper;
import com.zjdiepu.www.ibiz.dh.IDhInsuranceRenewalService;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.base.ext.SysUserExt;
import com.zjdiepu.www.model.dh.dto.DhInsuranceRenewal;
import com.zjdiepu.www.model.dh.ext.DhInsuranceRenewalExt;
import com.zjdiepu.www.model.other.dto.OtherTaskAllocation;

/**
 * 待续保列表Service层操作实现<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年05月17日 10时36分<br/>
 * @since 1.0<br/>
 */
@Service
public class DhInsuranceRenewalServiceImpl extends BaseService implements IDhInsuranceRenewalService {
	public static final Logger logger = LoggerFactory.getLogger(DhInsuranceRenewalServiceImpl.class);

	@Autowired
	private DhInsuranceRenewalMapper dhInsuranceRenewalMapper;
	@Autowired
	private SysUserMapper sysUserMapper;
	@Autowired
	private OtherTaskAllocationMapper otherTaskAllocationMapper;
	
	
	@Override
	public ApiResponse saveAllocation(String id, String operatorId,
			String operatorName, AbstractSysUser currentUser) {
		DhInsuranceRenewal dhInsuranceRenewal = new DhInsuranceRenewal();
		String userId = currentUser.getId();
		String userName=  currentUser.getName();
    	dhInsuranceRenewal.initUpdateData(userId, userName);
    	dhInsuranceRenewal.setOperatorId(operatorId);
    	dhInsuranceRenewal.setOperatorName(operatorName);
    	dhInsuranceRenewal.setAcceptDate(new Date());
    	List<String> ids = Arrays.asList(id.split(","));
    	dhInsuranceRenewalMapper.updateCommonBatch(dhInsuranceRenewal, ids);
    	List<OtherTaskAllocation> otherTaskAllocations = new ArrayList<OtherTaskAllocation>();
    	for(String id_ : ids) {
    		OtherTaskAllocation otherTaskAllocation = new OtherTaskAllocation();
    		otherTaskAllocation.initInsertData(userId, userName);
    		otherTaskAllocation.setModeId(ModeIDType.XUBAO.getCode());
    		otherTaskAllocation.setDataid(id_.trim());
    		otherTaskAllocation.setAlloterId(currentUser.getId());
    		otherTaskAllocation.setAlloterName(currentUser.getName());
    		otherTaskAllocation.setReceiverId(operatorId);
    		otherTaskAllocation.setReceiverName(operatorName);
    		otherTaskAllocations.add(otherTaskAllocation);
    	}
    	if(CollectionUtils.isNotEmpty(otherTaskAllocations)){
    		otherTaskAllocationMapper.insertBatch(otherTaskAllocations);
    	}
    	return ApiResponse.success(true);
	}
	@Override
	public void updateApplyToAllCation(int allocationNum, SysUser sysUser) {
		DhInsuranceRenewalExt dhInsuranceRenewalExt = new DhInsuranceRenewalExt();
		dhInsuranceRenewalExt.withOutPage();
        dhInsuranceRenewalExt.setBaseWhere();
        dhInsuranceRenewalExt.notAllocation();
        dhInsuranceRenewalExt.setStatusRenewal(InsuranceStatus.DAI_BAO.getCode());
        dhInsuranceRenewalExt.setOrderSql(" CREATED DESC ");
        List<DhInsuranceRenewal> dhInsuranceRenewals = dhInsuranceRenewalMapper.selectByExt(dhInsuranceRenewalExt);
        
        int dhInsuranceRenewalCounts = dhInsuranceRenewals.size();
		for(int i = 0; i < allocationNum && dhInsuranceRenewalCounts > 0; i++) {
//        	int nextBusinessInt = random.nextInt(dhInsuranceRenewalCounts);
        	DhInsuranceRenewal randomDhInsuranceRenewal = dhInsuranceRenewals.get(i);
        	randomDhInsuranceRenewal.initUpdateData(sysUser.getId(), sysUser.getName());
        	randomDhInsuranceRenewal.setOperatorId(sysUser.getId());
        	randomDhInsuranceRenewal.setOperatorName(sysUser.getUname());
        	randomDhInsuranceRenewal.setAcceptDate(new Date());
        	
        	dhInsuranceRenewals.remove(randomDhInsuranceRenewal);
        	dhInsuranceRenewalCounts--;
        	
        	
        	dhInsuranceRenewalMapper.updateByPrimaryKeySelective(randomDhInsuranceRenewal);
		}
		
		
	}
	
	@Override
	public void updateForApplyAllocation(int allocationNum, SysUser sysUser) {
    	DhInsuranceRenewalExt dhInsuranceRenewalExt = new DhInsuranceRenewalExt();
		dhInsuranceRenewalExt.withOutPage();
        dhInsuranceRenewalExt.setBaseWhere();
        dhInsuranceRenewalExt.notAllocation();
        List<DhInsuranceRenewal> dhInsuranceRenewals = dhInsuranceRenewalMapper.selectByExt(dhInsuranceRenewalExt);
        
        Random random = new Random();
        int dhInsuranceRenewalCounts = dhInsuranceRenewals.size();
        List<OtherTaskAllocation> otherTaskAllocations = new ArrayList<OtherTaskAllocation>();
		for(int i = 0; i < allocationNum && dhInsuranceRenewalCounts > 0; i++) {
        	int nextBusinessInt = random.nextInt(dhInsuranceRenewalCounts);
        	DhInsuranceRenewal randomDhInsuranceRenewal = dhInsuranceRenewals.get(nextBusinessInt);
        	randomDhInsuranceRenewal.initUpdateData(sysUser.getId(), sysUser.getName());
        	randomDhInsuranceRenewal.setOperatorId(sysUser.getId());
        	randomDhInsuranceRenewal.setOperatorName(sysUser.getUname());
        	randomDhInsuranceRenewal.setAcceptDate(new Date());
        	
        	dhInsuranceRenewals.remove(randomDhInsuranceRenewal);
        	dhInsuranceRenewalCounts--;
        	
        	OtherTaskAllocation otherTaskAllocation = new OtherTaskAllocation();
    		otherTaskAllocation.initInsertData(sysUser.getId(), sysUser.getName());
    		otherTaskAllocation.setModeId(ModeIDType.XUBAO.getCode());
    		otherTaskAllocation.setDataid(randomDhInsuranceRenewal.getId());
    		otherTaskAllocation.setAlloterId(sysUser.getId());
    		otherTaskAllocation.setAlloterName(sysUser.getName());
    		otherTaskAllocation.setReceiverId(sysUser.getId());
    		otherTaskAllocation.setReceiverName(sysUser.getUname());
    		otherTaskAllocations.add(otherTaskAllocation);
        	
        	dhInsuranceRenewalMapper.updateByPrimaryKeySelective(randomDhInsuranceRenewal);
		}
		
    	if(CollectionUtils.isNotEmpty(otherTaskAllocations)){
    		otherTaskAllocationMapper.insertBatch(otherTaskAllocations);
    	}
		
	}
	@Override
	public void updateForRandomAllocation(int allocationNum, SysUser sysUser) {
		String orgId = sysUser.getOrgId();
    	SysUserExt sysUserExt = new SysUserExt();
    	sysUserExt.setBaseWhere();
    	sysUserExt.withOutPage();
    	sysUserExt.setOrgId(orgId);
    	List<SysUser> sysUsers = sysUserMapper.selectByExt(sysUserExt);
    	int userCounts = sysUsers.size();
    	
    	Random random = new Random();
    	DhInsuranceRenewalExt dhInsuranceRenewalExt = new DhInsuranceRenewalExt();
    	dhInsuranceRenewalExt.withOutPage();
        dhInsuranceRenewalExt.setBaseWhere();
        dhInsuranceRenewalExt.notAllocation();
        List<DhInsuranceRenewal> dhInsuranceRenewals = dhInsuranceRenewalMapper.selectByExt(dhInsuranceRenewalExt);
        int dhInsuranceRenewalCounts = dhInsuranceRenewals.size();
        List<OtherTaskAllocation> otherTaskAllocations = new ArrayList<OtherTaskAllocation>();
    	if(userCounts > 0) {
    		for(int i = 0; i < allocationNum && dhInsuranceRenewalCounts > 0; i++) {
	    		int nextUserIndex = random.nextInt(userCounts);
	    		SysUser randomUser = sysUsers.get(nextUserIndex);
	        	int nextBusinessInt = random.nextInt(dhInsuranceRenewalCounts);
	        	DhInsuranceRenewal randomDhInsuranceRenewal = dhInsuranceRenewals.get(nextBusinessInt);
	        	randomDhInsuranceRenewal.initUpdateData(sysUser.getId(), sysUser.getName());
	        	randomDhInsuranceRenewal.setOperatorId(randomUser.getId());
	        	randomDhInsuranceRenewal.setOperatorName(randomUser.getUname());
	        	randomDhInsuranceRenewal.setAcceptDate(new Date());
	        	
	        	dhInsuranceRenewals.remove(randomDhInsuranceRenewal);
	        	dhInsuranceRenewalCounts--;
	        	
	        	OtherTaskAllocation otherTaskAllocation = new OtherTaskAllocation();
	    		otherTaskAllocation.initInsertData(sysUser.getId(), sysUser.getName());
	    		otherTaskAllocation.setModeId(ModeIDType.XUBAO.getCode());
	    		otherTaskAllocation.setDataid(randomDhInsuranceRenewal.getId());
	    		otherTaskAllocation.setAlloterId(sysUser.getId());
	    		otherTaskAllocation.setAlloterName(sysUser.getName());
	    		otherTaskAllocation.setReceiverId(randomUser.getId());
	    		otherTaskAllocation.setReceiverName(randomUser.getUname());
	    		otherTaskAllocations.add(otherTaskAllocation);
	        	
	        	dhInsuranceRenewalMapper.updateByPrimaryKeySelective(randomDhInsuranceRenewal);
    		}
    	}
    	
    	if(CollectionUtils.isNotEmpty(otherTaskAllocations)){
    		otherTaskAllocationMapper.insertBatch(otherTaskAllocations);
    	}
		
	}
	@Override
	public void saveUpdateAndDelete(DhInsuranceRenewal dhInsuranceRenewal, OperateType operType) {
		switch (operType) {
		case add:
			dhInsuranceRenewal.initInsertData(dhInsuranceRenewal.getModifier(), dhInsuranceRenewal.getModifierName());
			dhInsuranceRenewalMapper.insert(dhInsuranceRenewal);
			break;
		case edit:
			dhInsuranceRenewal.initUpdateData(dhInsuranceRenewal.getModifier(), dhInsuranceRenewal.getModifierName());
			// 影响的记录数
			int updateCount = dhInsuranceRenewalMapper.updateByPrimaryKeySelective(dhInsuranceRenewal);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		case delete:
			dhInsuranceRenewal.initDeleteData(dhInsuranceRenewal.getModifier(), dhInsuranceRenewal.getModifierName());
			// 影响的记录数
			int deleteCount = dhInsuranceRenewalMapper.updateByPrimaryKeySelective(dhInsuranceRenewal);
			if(deleteCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(deleteCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		default:
			break;
		}
	}
	
	@Override
	public List<DhInsuranceRenewal> selectByExt(DhInsuranceRenewalExt dhInsuranceRenewalExt) {
		return dhInsuranceRenewalMapper.selectByExt(dhInsuranceRenewalExt);
	}
	
	@Override
	public int countByExt(DhInsuranceRenewalExt dhInsuranceRenewalExt){
		return dhInsuranceRenewalMapper.countByExt(dhInsuranceRenewalExt);
	}
	
	@Override
	public DhInsuranceRenewal selectById(String id) {
		return dhInsuranceRenewalMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void clearEmpty(Set<String> fieldNames, String id) {
		if(CollectionUtils.isNotEmpty(fieldNames)){
			dhInsuranceRenewalMapper.clearEmpty(fieldNames, id);
		}
	}
	
	@Override
	public int countRefined(DhInsuranceRenewal dhInsuranceRenewal) {
		return dhInsuranceRenewalMapper.countRefined(dhInsuranceRenewal);
	}

	@Override
	public DhInsuranceRenewal selectRefined(DhInsuranceRenewal dhInsuranceRenewal) {
		return dhInsuranceRenewalMapper.selectRefined(dhInsuranceRenewal);
	}
	
	@Override
	public int deletedRefined(DhInsuranceRenewal dhInsuranceRenewal) {
		return dhInsuranceRenewalMapper.deletedRefined(dhInsuranceRenewal);
	}

	@Override
	public boolean repeat(DhInsuranceRenewal dhInsuranceRenewal) {
		int count = countRefined(dhInsuranceRenewal);
		if(count > 1) {
			return true;
		}
		if(count == 0) {
			return false;
		}
		
		if(StringUtils.isBlank(dhInsuranceRenewal.getId())) {
			return true;
		}
		DhInsuranceRenewal dbItem = selectRefined(dhInsuranceRenewal);
		if(null == dbItem) {
			return false;
		}
		return !dhInsuranceRenewal.getId().equals(dbItem.getId());
	}
	
	@Override
	public int updateBatch(String modifier, String modifierName, Integer dpStatus, List<String> ids) {
		Integer current = (int)(System.currentTimeMillis() / 1000);
		return dhInsuranceRenewalMapper.updateBatch(modifier, modifierName, current, dpStatus, ids);
	}
	
	@Override
	public int insertBatch(List<DhInsuranceRenewal> dhInsuranceRenewals) {
		return dhInsuranceRenewalMapper.insertBatch(dhInsuranceRenewals);
	}
}
